<style src="./index.scss" lang="scss" scoped rel="stylesheet/scss"></style>
<template src="./index.html"></template>

<script>
export default {
  props: {
    fileList: {
      type: Array,
      default: [],
    },

    accept: {
      type: String,
      required: "*",
    },

    size: String,
    multiple: Boolean,

    onChange: Function,
    name: String
  },
  data() {
    return {};
  },
  methods: {

    // 添加文件
    fileChange(e) {
      let files = e.target.files;
      if (files.length) {
        this.checkIfCanUpload(files);
      }

    },

    //  移除文件
    remove(index) {
       this.fileList.splice(index, 1);
    },

    //  检测文件
    checkIfCanUpload(files) {
      //  只能处理单个文件格式，需要优化
      for(let i=0; i<files.length; i++){
          if(this.accept !== "" && files[i].type !== this.accept){
            this.$vFN.Tools.messageError("请上传正确的文件格式");
            break
          }
          if(this.size !== "" && files[i].size > this.size){
            this.$vFN.Tools.messageError("文件过大,请压缩文件");
            break
          }
      }

     this.transform(files)
    },



    //  数据重构
    transform(files) {
    let reader = new FileReader();

    for(let i=0; i<files.length; i++){
        
        reader.readAsDataURL(files[i]);
        reader.onload = (e) => { 
            this.fileList.push({
                 name: files[i].name,
                 size: files[i].size,
                 base64: e.target.result,
                 type: files[i].type
            })
        }
     }
    },

    // 点击触发表单
    clickUpload(){
        let fileElem = document.getElementById("my-upload");
        fileElem.click()
    },

  },
  mounted() {
  },
};
</script>
